package com.qdsgjsfk.vision.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.StartVision;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.ui.dialog.DistanceDialog;
import com.qdsgjsfk.vision.ui.dialog.VisionModelDialog;
import com.qdsgjsfk.vision.ui.fragment.DiopterFragment;
import com.qdsgjsfk.vision.ui.fragment.VisionFragment;
import com.qdsgjsfk.vision.util.Constant;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.StudentClassResponse;
import com.rest.response.StudentInfoResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import util.PreferencesHelper;
import util.ServiceUtil;

/**
 * 筛查信息界面
 * Created by HP on 2018/10/7.
 */

public class StudentDetailActivity extends BaseActivity {
    @BindView(R.id.timeline_tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.timeline_viewpager)
    ViewPager mViewPager;

    @BindView(R.id.tv_stu_info)
    TextView tv_stu_info;
    @BindView(R.id.distance)
    TextView distance;
    @BindView(R.id.tv_stu_name)
    TextView tvStuName;
    @BindView(R.id.tv_stu_class)
    TextView tvStuClass;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.icon_switch)
    ImageView iconSwitch;
    @BindView(R.id.icon_obtain)
    ImageView iconObtain;
    @BindView(R.id.title)
    RelativeLayout title;
    private VisionModelDialog mVisionModelDialog;
    private DistanceDialog mDistanceDialog;
    //    long classId;
    String studentId;
    String taskId;
    int tab;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_student_detail;
    }

    @Override
    protected void initViews() {
        distance.setVisibility(View.GONE);
        mViewPager.setAdapter(new StudentDetailAdapter(this, getSupportFragmentManager()));
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        //setIndicatorWidth( mTabLayout, 60 );

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
//                    EventBus.getDefault().postSticky( new BlueTooth( "", 5 ) );
                    iconSwitch.setVisibility(View.VISIBLE);
                    iconObtain.setVisibility(View.INVISIBLE);
                } else if (position == 1) {
                    if (BaseApplication.isHandheldScreenerConnected) {
                        iconObtain.setVisibility(View.VISIBLE);
                    }
                    iconSwitch.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //1按下时调用，抬起时如果发生了滑动值会变为2（不发生滑动不会有2），滑动结束时变为0
                Log.e("ScrollStateChanged", state + "");
            }
        });
//        btnBack.setOnClickListener( new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //通知视力好屈光页面，返回键
//                EventBus.getDefault().postSticky( new BlueTooth( "", 4 ) );
//                //Toast.makeText( StudentDetailActivity.this, "ddddd", Toast.LENGTH_SHORT ).show();
//            }
//        } );
        if (tab == -1) {
            mViewPager.setCurrentItem(BaseApplication.currentTab);
            Objects.requireNonNull(mTabLayout.getTabAt(BaseApplication.currentTab)).select();
        } else {
            mViewPager.setCurrentItem(tab);
            Objects.requireNonNull(mTabLayout.getTabAt(tab)).select();
        }
    }

    public void setmViewPager(int i) {
        mViewPager.setCurrentItem(i);
        Objects.requireNonNull(mTabLayout.getTabAt(i)).select();
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
//        classId = getIntent().getLongExtra("classId", 0);
        studentId = getIntent().getStringExtra("studentId");
        taskId = getIntent().getStringExtra("taskId");
        tab = getIntent().getIntExtra("tab", -1);
//        getStudentById();
        BaseApplication.lastActivity = 1;
        getInfo();
        if (!ServiceUtil.isServiceExisted(this, "com.qdsgjsfk.vision.service.SocketService")) {
            stopService(new Intent(this, SocketService.class));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, SocketService.class));
            } else {
                startService(new Intent(this, SocketService.class));
            }
        }
    }

    /**
     * 获取学生筛查信息（屈光 更新）
     *
     * @time 2020/5/27 13:46
     */
    private void getInfo() {
        RestProxy.getInstance().getStudentInfoQG(studentId + "", taskId, new Observer<StudentInfoResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentInfoResponse studentInfoResponse) {
                tvStuName.setText(studentInfoResponse.data.studentName);
                tvStuClass.setText(studentInfoResponse.data.fullClassName);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError(e, StudentDetailActivity.this);

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick(R.id.icon_switch)
    void icon_switch() {
        showModelDialog();
    }


    @OnClick(R.id.icon_obtain)
    void icon_ontain() {
        EventBus.getDefault().post(new BlueTooth(PreferencesHelper.getInstance().getString(this, "machineIP"), Constant.IP_VS100));
    }

    /**
     * 筛查模式弹框
     *
     * @time 2020/6/23 14:15
     */
    private void showModelDialog() {
        mVisionModelDialog = VisionModelDialog.newInstance();
//        mVisionModelDialog.setmListener(new VisionModelDialog.OnItemClickListener() {
//            @Override
//            public void onConfirm() {
//                EventBus.getDefault().postSticky(new ModeChange(PreferencesHelper.getInstance().getInt(mContext, Constant.MODE, 1)));
//            }
//
//            @Override
//            public void onCancel() {
//
//            }
//        });
        mVisionModelDialog.show(getSupportFragmentManager(), "mVisionModelDialog");
    }

    private void showDistanceDialog() {
        mDistanceDialog = DistanceDialog.newInstance();
        mDistanceDialog.show(getSupportFragmentManager(), "mDistanceDialog");
        mDistanceDialog.setmListener(new DistanceDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                if (BaseApplication.currentDistance == 3) {
                    distance.setText("3m");
                } else {
                    distance.setText("5m");
                }
            }

            @Override
            public void onCancel() {

            }
        });
    }


    class StudentDetailAdapter extends FragmentPagerAdapter {
        private static final int PAGE_COUNT = 2;

        StudentDetailAdapter(Context context, FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return VisionFragment.newInstance(studentId, taskId, "0");
                case 1:
                    return DiopterFragment.newInstance(studentId, taskId, "1");
//                case 2:
//                    return OtherChooseFragment.newInstance( studentId, taskId );
                default:
                    return new VisionFragment();
            }
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "视力";
                case 1:
                    return "屈光";
//                case 2:
//                    return "其他";
                default:
                    return "";
            }
        }

    }

    @OnClick(R.id.distance)
    void distance() {
        showDistanceDialog();
    }

    @OnClick(R.id.icon_connect_device)
    void btn_connect_device() {
        startActivity(DeviceTypeActivity.class);
        BaseApplication.studentId = studentId;
        BaseApplication.taskId = taskId;
//        finish();
    }

    private void getStudentById() {
        RestProxy.getInstance().getStudentById(studentId + "", PreferencesHelper.getInstance().getString(this, "token"), new Observer<StudentClassResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(StudentClassResponse studentClassResponse) {
                tv_stu_info.setText(studentClassResponse.data.remark + "  " + studentClassResponse.data.name);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError(e, StudentDetailActivity.this);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        try {
            //这里写可能出现异常的语句
            BaseApplication.currentTab = mTabLayout.getSelectedTabPosition();
        } catch (Exception e) {
            // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
            e.printStackTrace();
        }

        super.onDestroy();
    }

    //粘性事件的接收
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(StartVision event) {
        Log.e("StartVision------", event.Start + "");
        if (event.Start == 1) {
            iconSwitch.setVisibility(View.INVISIBLE);
        } else if (event.Start == 0) {
            iconSwitch.setVisibility(View.VISIBLE);
        } else if (event.Start == 3) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BlueTooth event) {
        LogUtil.e("onMessageEvent");
        if (event.type == Constant.CODE_WS_SUCCESS) {
            ToastUtil.showToastCenter(mContext, event.output);
        }
    }

    //
//    //设置返回键动作（防止按返回键直接退出程序)
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO 自动生成的方法存根
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (true) {//当webview不是处于第一页面时，返回上一个页面
//
//                return true;
//            } else {//当webview处于第一页面时
//                finish();
//            }
//
//
//        }
//        return super.onKeyDown( keyCode, event );
//    }
    @Override
    protected void onResume() {
        super.onResume();
        if (tab == 1 && BaseApplication.isHandheldScreenerConnected) {
            iconObtain.setVisibility(View.VISIBLE);
        } else {

        }
        LogUtil.e("serviceStuDetail---" + ServiceUtil.isServiceExisted(this, "com.qdsgjsfk.vision.service.SocketService"));
    }

//    @Override
//    public void onBackPressed() {
////        super.onBackPressed();
//    }
}
